﻿using System;
using System.IO;
using System.Text;
using CSharpLogger.Common;

namespace CSharpLogger
{
    /// <summary>
    /// Implements <see cref="IFileWrapper"/> to wrap some <see cref="System.IO"/> methods.
    /// </summary>
    public class FileWrapper : IFileWrapper
    {
        /// <summary>
        /// Wrapper method for method <see cref="TextWriter.WriteLine"/>
        /// </summary>
        /// <param name="path">Full path and file name</param>
        /// <param name="message">Message to be logged</param>
        /// <param name="level">Indicates current messageg log level</param>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="ArgumentException"></exception>
        /// <exception cref="NotSupportedException"></exception>
        /// <exception cref="FileNotFoundException"></exception>
        /// <exception cref="IOException"></exception>
        /// <exception cref="SecurityException"></exception>
        /// <exception cref="DirectoryNotFoundException"></exception>
        /// <exception cref="UnauthorizedAccessException"></exception>
        /// <exception cref="PathTooLongException"></exception>
        /// <exception cref="ArgumentOutOfRangeException"></exception>
        /// <exception cref="FormatException"></exception>
        public void WriteLog(string path, string message, LogLevel level)
        {
            using (Stream fs = new FileStream(path, FileMode.Append, FileAccess.Write))
            {
                using (TextWriter tw = new StreamWriter(fs, Encoding.ASCII))
                {
                    try
                    {
                        tw.WriteLine("{0:MM/dd/yy H:mm:ss.fff zzz} {1} {2}", new object[] { DateTime.Now, level, message });
                        tw.Close();
                    }
                    catch (Exception e)
                    {
                        throw new CSharpLoggerException("FileWrapper.WriteLog", e);
                    }
                }
            }
        }
    }
}
